﻿using AutoMapper;
using MediatR;
using Provenance.Domain.Slaughter;
using Provenance.ErrorCount;
using Provenance.Infra.Interfaces.Slaughter;
using Provenance.Read.Api.Application.Command.Slaughter;

namespace Provenance.Read.Api.Application.CommandHandler.Slaughter
{
    public class BackSlaugtherEnterpriseCommandHandler : IRequestHandler<BackSlaugtherEnterpriseCommand, ApiResult<SlaughterEnterprise>>
    {
        private readonly ISlaughterEnterpriseRepository _slaughterEnterpriseRepository;
        private readonly ILogger<BackSlaugtherEnterpriseCommandHandler> _logger;
        private readonly IMapper _mapper;
        public BackSlaugtherEnterpriseCommandHandler(ISlaughterEnterpriseRepository slaughterEnterpriseRepository, ILogger<BackSlaugtherEnterpriseCommandHandler> logger, IMapper mapper)
        {
            _slaughterEnterpriseRepository = slaughterEnterpriseRepository;
            _logger = logger;
            _mapper = mapper;
        }
        public async Task<ApiResult<SlaughterEnterprise>> Handle(BackSlaugtherEnterpriseCommand request, CancellationToken cancellationToken)
        {
            try
            {
                var obj = await _slaughterEnterpriseRepository.GetAsync(x => x.ProductInfoId == request.ProductInfoId);
                if (obj == null)
                {
                    return ApiResult<SlaughterEnterprise>.Failure("Slaughter enterprise not found");
                }
                return ApiResult<SlaughterEnterprise>.Success(obj);
            }
            catch (Exception ex)
            {
                _logger.LogError("Error getting slaughter enterprise", ex.Message);
                return ApiResult<SlaughterEnterprise>.Failure(ex.Message);
            }
        }
    }
}
